package com.wzy.Controller;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.wzy.entity.Blog;
import com.wzy.entity.Hero;
import com.wzy.entity.Province;
import com.wzy.service.HeroService;
import com.wzy.service.ProvinceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wzy
 * @since 2021-02-09
 */
@Api("hero页面")
@Slf4j
@Controller
public class HeroController {

    @Autowired
    private HeroService heroService;
    @Autowired
    private ProvinceService provinceService;


    @Autowired
    RedisTemplate redisTemplate;

    /**
     *  跳转到英雄名录行页面
     *
     * @return
     */
    @ApiOperation("Hero数据渲染")
    @GetMapping("/hero/{current}/{limit}")
    public String routerheroPage(Province province,
                                 @PathVariable Long current,
                                 @PathVariable Long limit,
                                 Model model) {
        List<Province> listProvince = null;
        //先从缓存中查省份信息
        listProvince =  redisTemplate.opsForList().range("provinces",(long)0,(long)-1);
        //若缓存中无省份信息
        if (listProvince.size()==0) {
            //查数据库
            listProvince = provinceService.list((Wrapper<Province>) null);
            //        将省份信息放入缓存,设置过期时间为30分钟
            for (Province p : listProvince) {
                redisTemplate.opsForList().leftPush("provinces",p);
            }
            redisTemplate.expire("provinces",30 , TimeUnit.MINUTES);

        }

        //分页查询
        Page<Hero> heroPage = new Page<>(current, limit);
        //当前省份的id
        Long curProvinceId = province.getProvinceId();

        log.error(province.toString());

        //如果传递过来数据中无省份id，则进行默认显示，显示list集合中的第一个省份所对应的英雄
        if (curProvinceId == null) {
            curProvinceId = listProvince.get(0).getProvinceId();
            //根据默认省份id获取hero
            heroService.getHeroListByProviceId(curProvinceId, heroPage);
        } else {
            //传递过来的数据中有省份id，显示省份对应的英雄信息
            heroService.getHeroListByProviceId(curProvinceId, heroPage);
        }
        //按照查出省份对应的hero
        model.addAttribute("heros", heroPage.getRecords());
        model.addAttribute("total", heroPage.getTotal());
        model.addAttribute("hasNext", heroPage.hasNext());
        model.addAttribute("hasPrevious", heroPage.hasPrevious());
        model.addAttribute("provinces", listProvince);
        model.addAttribute("curProvinceId", curProvinceId);

        return "hero";
    }


}

